<script setup>
import {ref, onMounted, computed, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import resourceService from '@/services/resourceService.js';
import {userManager} from "@/utils/user.js";
import {
  ElRow, ElCol, ElCard, ElTag, ElButton, ElIcon, ElAvatar,
  ElSkeleton, ElSkeletonItem, ElEmpty, ElMessage, ElDivider, ElImage,
  ElSpace, ElText
} from 'element-plus';
import {Document, Download, User, Coin, Picture as IconPicture} from '@element-plus/icons-vue';
import VuePdfEmbed from 'vue-pdf-embed';

const route = useRoute();
const router = useRouter();
const resourceId = route.params.id;
const resource = ref(null);
const loading = ref(true);
const error = ref(null);
const textContent = ref('');
const textContentError = ref(false);

const fileType = computed(() => {
  if (!resource.value?.location) return 'unsupported';
  const url = resource.value.location.toLowerCase();
  const filename = url.substring(url.lastIndexOf('/') + 1).split('?')[0];
  const extension = '.' + filename.split('.').pop();

  if (['.mp4', '.webm', '.ogg'].includes(extension)) return 'video';
  if (extension === '.pdf') return 'pdf';
  if (['.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx'].includes(extension)) return 'office';
  if (['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.svg'].includes(extension)) return 'image';
  if (['.txt', '.md', '.json', '.js', '.css', '.html', '.xml', '.java', '.py', '.go'].includes(extension)) return 'text';
  return 'unsupported';
});

async function fetchTextContent() {
  if (fileType.value === 'text' && resource.value?.location) {
    textContentError.value = false;
    textContent.value = '正在加载文本内容...';
    try {
      const response = await fetch(resource.value.location);
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      textContent.value = await response.text();
    } catch (e) {
      console.error("Failed to fetch text content:", e);
      textContent.value = "";
      textContentError.value = true;
    }
  }
}

watch(resource, (newResource) => {
  if (newResource) fetchTextContent();
}, {immediate: true});

async function fetchResourceDetail() {
  if (!resourceId) {
    error.value = '无效的资源ID';
    loading.value = false;
    return;
  }
  loading.value = true;
  try {
    const response = await resourceService.getResourceById(resourceId);
    if (response && response.success) {
      resource.value = response.data;
      const userId = userManager.getUserId();
      if (userId && resource.value.major) {
        try {
          await resourceService.logResourceView(userId, resource.value.major);
        } catch (logError) {
          console.error("记录资源浏览行为失败:", logError);
        }
      }
    } else {
      throw new Error(response.message || '资源不存在或已被删除');
    }
  } catch (err) {
    console.error('获取资源详情失败:', err);
    error.value = err.message || '加载资源失败，请稍后重试。';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
}

onMounted(fetchResourceDetail);

const difficultyMap = {
  0: {text: '简单', type: 'success'},
  1: {text: '中等', type: 'primary'},
  2: {text: '困难', type: 'warning'},
  3: {text: '高阶', type: 'danger'},
};
const formatDifficulty = (value) => difficultyMap[value] || {text: '未知', type: 'info'};
const handleDownload = () => resource.value?.location && window.open(resource.value.location, '_blank');
</script>

<template>
  <div class="page-background">
    <div class="resource-show-page">
      <div class="back-button-right">
        <el-button type="primary" @click="router.back()">返回上一页</el-button>
      </div>
      <div v-if="loading" class="loading-skeleton">
        <el-row :gutter="24">
          <el-col :span="16">
            <el-skeleton-item variant="image" class="skeleton-preview"/>
          </el-col>
          <el-col :span="8">
            <el-skeleton :rows="6" animated/>
          </el-col>
        </el-row>
      </div>

      <div v-else-if="error" class="center-container">
        <el-empty :description="error">
          <el-button type="primary" @click="router.back()">返回上一页</el-button>
        </el-empty>
      </div>

      <div v-else-if="resource" class="resource-layout">
        <header class="resource-header">
          <h1 class="resource-title">{{ resource.title }}</h1>
          <el-space wrap>
            <el-tag effect="plain" size="small" round>{{ resource.major }}</el-tag>
            <el-tag :type="formatDifficulty(resource.difficulty).type" effect="plain" size="small" round>
              {{ formatDifficulty(resource.difficulty).text }}
            </el-tag>
          </el-space>
        </header>

        <el-row :gutter="32">
          <el-col :xs="24" :sm="24" :md="16">
            <div class="preview-area">
              <video v-if="fileType === 'video'" :src="resource.location" controls class="media-preview"></video>
              <vue-pdf-embed v-else-if="fileType === 'pdf'" :source="resource.location" class="pdf-preview"/>
              <el-image v-else-if="fileType === 'image'" :src="resource.location" fit="contain" class="media-preview"
                        :preview-src-list="[resource.location]" preview-teleported>
                <template #error>
                  <div class="file-placeholder">
                    <el-icon size="60">
                      <IconPicture/>
                    </el-icon>
                    <p>图片加载失败</p></div>
                </template>
              </el-image>
              <div v-else-if="fileType === 'text' && !textContentError" class="text-preview-wrapper">
                <pre><code>{{ textContent }}</code></pre>
              </div>
              <div v-else class="fallback-preview">
                <el-image :src="resource.coverImage" fit="cover" class="fallback-bg">
                  <template #error>
                    <div/>
                  </template>
                </el-image>
                <div class="fallback-overlay">
                  <div class="fallback-content">
                    <el-icon size="80">
                      <Document/>
                    </el-icon>
                    <p class="main-message">该文件类型不支持在线预览</p>
                    <p class="sub-message">请下载后在本地查看</p>
                  </div>
                </div>
              </div>
            </div>
          </el-col>

          <el-col :xs="24" :sm="24" :md="8">
            <div class="info-sidebar">
              <el-card shadow="never" class="info-card">
                <div class="publisher-section">
                  <el-avatar :icon="User" :size="48" :src="resource.publisherAvatar"/>
                  <div class="publisher-details">
                    <span class="publisher-name">{{ resource.publisherName || '匿名作者' }}</span>
                    <span class="publisher-id">ID: {{ resource.publisherId }}</span>
                  </div>
                </div>
                <el-divider/>
                <div class="credit-section">
                  <span class="credit-label">所需学分</span>
                  <span class="credit-value"><el-icon><Coin/></el-icon>{{ resource.credit || 0 }}</span>
                </div>
                <el-button type="primary" :icon="Download" size="large" @click="handleDownload" class="download-button">
                  立即下载
                </el-button>
              </el-card>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 页面整体布局 */
.page-background {
  background: linear-gradient(180deg, #f8f9fb 0%, #f4f6f9 100%);
  min-height: 100vh;
  padding: 24px;
}

.resource-show-page {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-skeleton, .center-container {
  padding-top: 40px;
}

.skeleton-preview {
  width: 100%;
  height: 60vh;
  border-radius: 12px;
}

.resource-header {
  margin-bottom: 24px;
}

.resource-title {
  margin: 0 0 12px 0;
  font-size: 28px;
  font-weight: 600;
  color: #202124;
}

/* 左侧内容区 */
.preview-area {
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  overflow: hidden;
  background-color: #fff;
  min-height: 70vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.media-preview, .pdf-preview {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
}

.pdf-preview {
  min-height: 70vh;
}

.text-preview-wrapper {
  width: 100%;
  height: 70vh;
  background-color: #282c34;
  color: #abb2bf;
  padding: 20px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.text-preview-wrapper pre {
  margin: 0;
  font-family: 'Operator Mono', 'Source Code Pro', Menlo, Monaco, Consolas, 'Courier New', monospace;
  font-size: 14px;
}

.file-placeholder, .fallback-preview {
  width: 100%;
  min-height: 70vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.fallback-preview {
  position: relative;
}

.fallback-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: blur(8px);
  transform: scale(1.1);
}

.fallback-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.fallback-content {
  color: #3c4043;
}

.main-message {
  font-weight: 500;
  font-size: 16px;
  margin-top: 16px;
}

.sub-message {
  margin-top: 8px;
  font-size: 14px;
  color: #5f6368;
}

/* 右侧侧边栏 */
.info-sidebar {
  position: sticky;
  top: 24px;
}

.info-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
}

.publisher-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.publisher-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.publisher-name {
  font-size: 1rem;
  font-weight: 500;
  color: #202124;
}

.publisher-id {
  font-size: 0.8rem;
  color: #5f6368;
}

.credit-section {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 20px;
}

.credit-label {
  font-size: 14px;
  color: #5f6368;
}

.credit-value {
  font-size: 28px;
  font-weight: 600;
  color: var(--el-color-danger);
  display: flex;
  align-items: center;
  gap: 6px;
}

.download-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.back-button-right {
  text-align: right;
  margin-bottom: 20px;
}

@media (max-width: 992px) {
  .info-sidebar {
    margin-top: 24px;
  }
}
</style>